﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using bmapi.HelperClass;
using bmapi.Models.DataEntity;
using bmapi.SQLServerAccess;
using static bmapi.Models.ShowModel;

namespace bmapi.Controllers
{
    [Route("personal"),JwtAuthActionFilter]
    public class PersonalController : PageController
    {
        [HttpGet]
        public HttpResponseMessage Get() 
        {
            int loginid = GetCrrentIDByToken();
            string sql = "select * from User_tb where login_id=@loginid";
            SQLCommand sc = new SQLCommand(sql, "@loginid",loginid);
            DataTable dt = sc.ExecuteScalars();
            User current = AssistFun.DataTableToList<User>(dt)[0];
            ShowStaffInfo myinfo = new ShowStaffInfo(current, MatchProNameByProCode(new List<int>() { current.code })[0]);
            return AssistFun.toJson(new { status = 200, tip = "成功", data = myinfo });
        }
        [HttpPut]
        public HttpResponseMessage Put(dynamic obj)
        {
            string name = obj.name.ToString();
            string password = obj.password.ToString();
            string phone = obj.phone.ToString();
            int loginid = GetCrrentIDByToken();
            User user = GetUserByLoginID(loginid);
            string phones = "";
            SQLCommand sc = null;
            if (phone != user.phone)
            {
                sc = new SQLCommand("select phone from User_tb where phone=@phone", "@phone", phone);
                phones = sc.ExecuteScalar();
                if(phones!=null)
                    return AssistFun.toJson(new { status = 201, tip = "已经存在该手机号", data = "" });
            }
            sc = new SQLCommand("update User_tb set name=@name,password=@pwd,phone=@phone where login_id=@login_id");
            sc.Add("@name", name);
            sc.Add("@pwd", password);
            sc.Add("@phone", phone);
            sc.Add("@login_id", loginid);
            if (sc.ExecuteNonQuery() != -1)
                return AssistFun.toJson(new { status = 200, tip = "成功", data = "" });
            else
                return AssistFun.toJson(new { status = 201, tip = "失败", data = "" });

        }
    }
}